<script lang="ts" setup>
/**
 * 修改密码弹框组件
 */
import { ref, watch } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import { ElDialog, ElForm, ElFormItem, ElInput, ElMessage, ElButton } from 'element-plus';
import { useUserStore } from '#/store/modules/user';

const props = defineProps<{
  open: boolean;
}>();

const emit = defineEmits<{
  (e: 'update:open', value: boolean): void;
  (e: 'success'): void;
}>();

// 监听 open 属性变化
watch(() => props.open, (newVal) => {
  console.log('Dialog open changed:', newVal);
});

// 表单数据
const formData = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
});

// 表单规则
const formRules: FormRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' },
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (_rule: any, value: string, callback: (error?: Error) => void) => {
        if (value !== formData.value.newPassword) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
};

const formRef = ref<FormInstance>();
const userStore = useUserStore();
const loading = ref(false);

// 处理表单提交
async function handleOk() {
  console.log('Handling OK');
  if (!formRef.value) return;

  try {
    loading.value = true;
    await formRef.value.validate();

    const result = await userStore.changePassword({
      oldPassword: formData.value.oldPassword,
      newPassword: formData.value.newPassword,
    });

    if (result) {
      ElMessage.success('密码修改成功');
      handleCancel();
      emit('success');
    }
  } catch (error: any) {
    if (error.message) {
      ElMessage.error(error.message);
    }
  } finally {
    loading.value = false;
  }
}

// 处理取消
function handleCancel() {
  console.log('Handling cancel');
  formRef.value?.resetFields();
  emit('update:open', false);
}
</script>

<template>
  <ElDialog
    :model-value="open"
    @update:model-value="(val: boolean) => emit('update:open', val)"
    title="修改密码"
    width="400px"
    :close-on-click-modal="false"
    @close="handleCancel"
    destroy-on-close
  >
    <ElForm
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      @submit.prevent
    >
      <ElFormItem label="原密码" prop="oldPassword">
        <ElInput v-model="formData.oldPassword" type="password" placeholder="请输入原密码" show-password />
      </ElFormItem>

      <ElFormItem label="新密码" prop="newPassword">
        <ElInput v-model="formData.newPassword" type="password" placeholder="请输入新密码" show-password />
      </ElFormItem>

      <ElFormItem label="确认新密码" prop="confirmPassword">
        <ElInput v-model="formData.confirmPassword" type="password" placeholder="请再次输入新密码" show-password />
      </ElFormItem>
    </ElForm>

    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="handleCancel">取消</ElButton>
        <ElButton type="primary" :loading="loading" @click="handleOk">
          确认
        </ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
